# encoding: utf-8

from typing import List, Dict, Any
from utils.ners import extract_one

ner_map = {"核心产品": "核心产品", "人名": "人名", "使用方法": "使用方法", "使用方式": "使用方法", "修饰": "修饰", "风格": "风格",
           "功能": "修饰", "品牌": "品牌", "型号": "型号", "地点": "地区", "售卖规格": "销售单位", "工艺": "工艺", "文化": "文化作品",
           "材质": "材质", "款式": "款式", "系列": "系列", "组织机构": "组织机构", "适用范围": "适用范围", "颜色": "颜色",
           "外观尺寸": "规格",
           }


def process_data(data: Dict[str, Any]) -> Dict[str, Any]:
    temp = {}
    ner_data = data.get("ner_data", {})
    for ner_data in ner_data.get("output", []):
        ner_type = ner_data.get("type", "")
        ner_span = ner_data.get("span", "")
        if ner_type == "":
            continue
        for key, value in ner_map.items():
            if key in ner_type:
                temp_list = temp.get(value, [])
                if not temp_list:
                    temp_list = []
                temp_list.append(ner_span)
                temp_list = [x.strip() for x in temp_list if x.strip()]
                temp[value] = temp_list
        if "产品" in ner_type and "核心产品" not in ner_type:
            temp_list = temp.get("产品", [])
            if not temp_list:
                temp_list = []
            temp_list.append(ner_span)
            temp["其他产品"] = temp_list
    data['ner_result'] = temp
    return data


def process_ner(text: str) -> Dict[str, List[str]]:
    # temp = {"颜色": ["a", "b", "c"]}
    temp = {}
    ner_result = extract_one(text)
    for ner_data in ner_result.get("output", []):
        ner_type = ner_data.get("type", "")
        ner_span = ner_data.get("span", "")
        if ner_type == "":
            continue
        for key, value in ner_map.items():
            if key in ner_type:
                temp_list = temp.get(value, [])
                if not temp_list:
                    temp_list = []
                temp_list.append(ner_span)
                temp_list = [x.strip() for x in temp_list if x.strip()]
                temp[value] = temp_list
        if "产品" in ner_type and "核心产品" not in ner_type:
            temp_list = temp.get("产品", [])
            if not temp_list:
                temp_list = []
            temp_list.append(ner_span)
            temp["其他产品"] = temp_list

    return temp


def is_same_sku(data: Dict, material_ner_data: Dict, mate_data: Dict, mate_sku_name: str) -> str:
    """
    return "true" or "false"
    """
    true = "true"
    false = "false"
    model = data.get("brandModel", "abcdefg")
    brand = data.get("brand", "")
    search_brands = material_ner_data.get("品牌", [])
    search_brands.append(brand)
    search_names = material_ner_data.get("核心产品", [])
    search_colors = material_ner_data.get("颜色", [])

    mate_brands = mate_data.get("品牌", [])
    mate_models = mate_data.get("型号", [])
    mate_names = mate_data.get("核心产品", [])
    mate_colors = mate_data.get("颜色", [])

    if not has_brand(search_brands, mate_brands):
        return false
    # 过滤型号
    if model not in mate_models:
        return false
    # 商品名称需要有交叉
    if not has_name(search_names, mate_names):
        return false
    # 判断颜色
    if not has_color(search_colors, mate_colors):
        return false
    # 判断 适用
    if not has_suit_for(brand, mate_sku_name):
        return false

    return true


def replace_strings(string: str) -> str:
    targets = ["_", "-", "/", "&", "@", " "]
    for target in targets:
        string = string.replace(target, "")

    return string


def has_brand(brands1: List[str], brands2: List[str]) -> bool:
    """
    brands2列表是否包含品牌
    """
    brands1 = [replace_strings(x.lower()) for x in brands1]
    brands2 = [replace_strings(x.lower()) for x in brands2]
    brands1 = get_all_brands(brands1)
    brands2 = get_all_brands(brands2)

    return bool(set(brands1) & set(brands2))


def get_all_brands(brands: List[str]) -> List[str]:
    temp = []
    for brand in brands:
        if "/" in brand:
            temp.extend(brand.split("/"))
        if "(" in brand:
            _brands = brand.split("(")
            for __brand in _brands:
                temp.append(__brand.replace(")", ""))
        if "（" in brand:
            _brands = brand.split("（")
            for __brand in _brands:
                temp.append(__brand.replace("）", ""))

    return temp


def has_name(names1: List[str], names2: List[str]) -> bool:
    """
    商品通用名
    """
    return bool(set(names1) & set(names2))


def has_color(colors1: List[str], colors2: List[str]) -> bool:
    """
    提前处理，颜色去掉'色'字，转set
    1、如果两个颜色都是空，true
    2、如果colors2颜色大于1，则false
    3、如果colors2出现的颜色都在colors1中，true
    """
    colors1 = list(set([x.replace("色", "") for x in colors1 if x and x.replace("色", "")]))
    colors2 = list(set([x.replace("色", "") for x in colors2 if x and x.replace("色", "")]))
    if not colors1 and not colors2:
        return True
    if len(colors2) > 1:
        return False
    has_all = True
    for color2 in colors2:
        if color2 not in colors1:
            has_all = False
    return has_all


def has_suit_for(brand_name, mate_sku_name: str) -> bool:
    """
    适用
    """

    if "适用" in mate_sku_name:
        try:
            if "/" in brand_name:
                brand_name = brand_name.split("/")[0]
            if "(" in brand_name:
                brand_name = brand_name.split("(")[0]
            if "（" in brand_name:
                brand_name = brand_name.split("（")[0]
            if "适用" + brand_name in mate_sku_name:
                return False
        except Exception as e:
            return False

    return True
